const queryUrl = "http://localhost:8080/subject/query"
const submitUrl = "http://localhost:8080/subject/submit"
const deleteUrl = "http://localhost:8080/subject/delete"
const confirmUrl = "http://localhost:8080/subject/confirm"
const identityIdUrl = 'http://localhost:8080/identify/id'


const header = {
    headers: {
        Authorization: localStorage.getItem("Authorization")
    }
};

const queryParams = {
    subjectName: "", // 初始值为空字符串
    showAll: 0, // 初始值为 0
    teacherName: "", // 初始值为空字符串
    orderBy: "id", // 初始排序字段为 "id"
    desc: 0, // 初始值为 0
    page: 1, // 初始页码为 1
    pageSize: 10 // 初始每页大小为 10
};

const submitParams = {
    name: "",
    difficulty: "",
    teacherId: ""
}

async function getIdentityId() {
    return new Promise((resolve, reject) => {
        const username = localStorage.getItem("LoginUser");
        const url = identityIdUrl + "?username=" + username;
        axios.get(url, header)
            .then((response) => {
                if (response.data.code === 0) {
                    resolve(response.data.data);
                } else {
                    reject(new Error("Error getting identity ID"));
                }
            })
            .catch((err) => {
                reject(err);
            });
    });
}

// 更新 queryParams 对象的值以反映表单输入
function updateQueryParams() {
    queryParams.subjectName = document.getElementById("subjectName").value;
    queryParams.showAll = document.getElementById("showAll").checked ? 1 : 0;
    queryParams.teacherName = document.getElementById("teacherName").value;
    queryParams.orderBy = document.getElementById("orderBy").value;
    queryParams.desc = document.getElementById("desc").checked ? 1 : 0;
    queryParams.page = parseInt(document.getElementById("page").value) || 1;
    queryParams.pageSize = parseInt(document.getElementById("pageSize").value) || 10;
}

function updateSubmitParams() {
    submitParams.name = document.getElementById("name").value
    submitParams.difficulty = document.getElementById("difficulty").value || 1
    submitParams.teacherId = localStorage.getItem("userId")
}

async function deleteSubject(id) {
    const teacherId = await getIdentityId();
    const url = deleteUrl + "?id=" + id + "&teacherId=" + teacherId;
    axios.delete(url, header)
        .then((response) => {
            if (response.data.code === 0) {
                alert(response.data.data);
                querySubject();
            } else {
                alert(response.data.msg);
            }
        })
        .catch((err) => {
            alert(err);
        })
}

var studentListMap = new Map();

function querySubject() {
    updateQueryParams();
    const url = `${queryUrl}?${Object.keys(queryParams).map(key => `${key}=${queryParams[key]}`).join('&')}`;
    axios.get(
        url,
        header
    ).then((response) => {
        if (response.data.code === 0) {
            const subjects = response.data.data; // 假设响应数据是一个包含课题信息的数组
            // 获取用于显示课题的表格
            const subjectTable = document.querySelector("#subjectList table tbody");
            // 清空表格内容，以便显示新的查询结果
            subjectTable.innerHTML = "";
            // 遍历课题数组，并创建课题元素并添加到容器中
            subjects.forEach((subject) => {
                const row = subjectTable.insertRow();
                const idCell = row.insertCell(0);
                const nameCell = row.insertCell(1);
                const difficultyCell = row.insertCell(2);
                const selectedCell = row.insertCell(3);
                const preStudentNameCell = row.insertCell(4);
                const studentNameCell = row.insertCell(5);
                const teacherNameCell = row.insertCell(6);
                const actionCell = row.insertCell(7);

                // 填充单元格内容
                idCell.textContent = subject.id;
                nameCell.textContent = subject.name;
                difficultyCell.textContent = subject.difficulty;
                selectedCell.textContent = subject.selected === 1 ? "是" : "否";
                let preStudentList = "";
                subject.preStudentName.forEach((e) => {
                    preStudentList += " " + e.realName;
                })
                preStudentNameCell.textContent = preStudentList || "N/A";
                studentNameCell.textContent = subject.studentName || "N/A";
                teacherNameCell.textContent = subject.teacherName || "N/A";
                studentListMap.set(subject.id, subject.preStudentName);

                // Add "删除" button for subjects without selected students
                if (subject.selected === 0) {
                    const deleteButton = document.createElement("button");
                    const confirmStudentButton = document.createElement("button");
                    deleteButton.classList.add("action-button");
                    confirmStudentButton.classList.add("action-button");
                    deleteButton.textContent = "删除";
                    confirmStudentButton.textContent = "选择学生";
                    deleteButton.addEventListener("click", () => deleteSubject(subject.id));
                    actionCell.appendChild(deleteButton);
                    confirmStudentButton.addEventListener("click", () => confirmStudent(subject.id));
                    actionCell.appendChild(confirmStudentButton);
                } else {
                    actionCell.textContent = "N/A"; // No action needed for selected subjects
                }
            });
        }

    }).catch((err) => {

    })
}

/**
 * 教师提交课题
 */
function submitSubject() {
    updateSubmitParams();
    axios.post(submitUrl, submitParams, header)
        .then((response) => {
            if (response.data.code === 0) {
                querySubject();
            } else {
                alert(response.data.msg);
            }
        })
        .catch((err) => {
            alert(err)
        })
}

/**
 * 根据课题ID查询学生List
 * @param subject 课题id
 * @returns {any} 学生List，包含id，code，realName
 */
function getPreStudentsById(subject) {
    return studentListMap.get(subject);
}

/**
 * 选择学生按钮，弹出菜单
 * @param subjectId
 */
function confirmStudent(subjectId) {
    const confirmStudentModal = document.getElementById('confirmStudentModal');

    const students = getPreStudentsById(subjectId);

    const studentList = document.getElementById('studentList');
    studentList.innerHTML = '';

    const selectElement = document.createElement('select');
    selectElement.setAttribute('id', 'selectedStudent');
    selectElement.setAttribute('name', 'selectedStudent');

    const defaultOption = document.createElement('option');
    defaultOption.setAttribute('value', '');
    defaultOption.textContent = '-- 请选择 --';
    selectElement.appendChild(defaultOption);

    students.forEach(student => {
        const option = document.createElement('option');
        option.setAttribute('value', student.id);
        option.textContent = student.realName + "(" + student.code + ")";
        selectElement.appendChild(option);
    });

    studentList.appendChild(selectElement);

    const confirmBtn = document.createElement('button');
    confirmBtn.textContent = '确认选择';
    confirmBtn.classList.add("action-button");
    confirmBtn.addEventListener('click', () => {
        const studentId = selectElement.value;
        confirmSelectedStudents(subjectId, studentId)
    });
    studentList.appendChild(confirmBtn);

    confirmStudentModal.style.display = 'block';
}

/**
 * 关闭选择学生弹窗
 */
function closeConfirmStudentModal() {
    const confirmStudentModal = document.getElementById('confirmStudentModal');
    confirmStudentModal.style.display = 'none';
}

/**
 * 确认选择学生
 * @param subjectId 课题id
 * @param studentId 学生id
 */
function confirmSelectedStudents(subjectId, studentId) {
    console.log(`Selected Student for Subject ID ${subjectId}: ${studentId}`);
    if(studentId != null && studentId !== "") {
        const teacherId = localStorage.getItem("userId");
        const url = confirmUrl + "?id=" + subjectId + "&studentId=" + studentId + "&teacherId=" + teacherId;
        axios.post(url, {}, header)
            .then((response) => {
                if(response.data.code === 0) {
                    alert("确认选择学生成功")
                    querySubject()
                } else {
                    alert(response.data.msg);
                }
            })
            .catch((err) => {
                alert(err);
            })
    }
    closeConfirmStudentModal();
}

